package org.beetl.json.action;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.beetl.json.ActionReturn;
import org.beetl.json.JsonWriter;
import org.beetl.json.OutputNode;
import org.beetl.json.node.PojoAttributeNode;
import org.beetl.json.node.PojoNode;

public class ClassCycleIncludeAction implements IClassAction,ICycleAction {

	String[] names = null;
	public ClassCycleIncludeAction(String names){
		this.names = names.split(",");
	}
	
	@Override
	public int getIndex() {
		// TODO Auto-generated method stub
		return 3;
	}

	@Override
	public ActionReturn doit(OutputNode thisNode) {
		PojoNode node = (PojoNode)thisNode; 
		node.setCycleCheck(true);
		node.setCycleAction(this);
		return new ActionReturn(node.getAttrs());
	}

	@Override
	public void cycleRender(PojoNode pojo,Object obj, JsonWriter w) throws IOException {
		w.writeScopeChar('{');
		List<PojoAttributeNode> attrs =  pojo.getAttrs();
		Iterator<PojoAttributeNode> it = attrs.iterator();
		if(!it.hasNext()){
			w.writeScopeChar('}');
			return ;
		}
		boolean firstWrite = false ;
		while(true){			
			PojoAttributeNode node = it.next();
			if(containAttr(node.getAttrName())){
				node.render(obj, w);
				firstWrite = true ;
			}		
			if(!it.hasNext()){
				w.writeScopeChar('}');
				return ;
			}else{
				if(firstWrite)w.writeComma();
			}
		
		}
		
	}
	
	private boolean containAttr(String attr){
		for(String s:names){
			if(s.equals(attr)){
				return true;
			}
		}
		return false;
	}

}
